import os  
import time  
  
# 读取年份  
with open("启动参数.txt", "r") as f:  
    for line in f.readlines():  
        if "年份" in line:  
            年份 = line.split("=")[1].strip("\n")  
  
# 缓存字典，用于存储已找到的PDF文件路径  
pdf_cache = {}  
  
# 缓存文件路径  
cache_file_path = "质保书缓存目录.txt"  
  
# 尝试从缓存文件中读取PDF文件列表  
def read_cache():  
    if os.path.exists(cache_file_path):  
        with open(cache_file_path, "r") as cache_file:  
            cache_data = cache_file.read()  
            if cache_data and 年份 in cache_data:  
                global pdf_cache  
                pdf_cache[年份] = cache_data.split("\n")  
                print("已加载缓存中的PDF文件列表。")  
                return True  
    return False  
  
# 将PDF文件列表写入缓存文件  
def write_cache(pdf_list):  
    with open(cache_file_path, "w") as cache_file:  
        for path in pdf_list:  
            cache_file.write(path + "\n")  
    print("已更新并保存质保书缓存目录。")  
  
# 预生成PDF文件列表的函数  
def generate_pdf_list(year):  
    pdf_list = []  
    for month in range(1, 13):  
        month_str = str(month)
        path = os.path.join(os.getcwd(), year, f"{month_str}月")  
        if os.path.exists(path):  
            for root, dirs, files in os.walk(path):  
                for file in files:  
                    if file.endswith(".pdf"):  
                        pdf_list.append(os.path.join(root, file))  
    return pdf_list  
  
# 初始化PDF文件列表缓存  
if not read_cache():  
    pdf_cache[年份] = generate_pdf_list(年份)  
    write_cache(pdf_cache[年份])  
  
while True:  
    filename = input("请输入你需要打开的质保书名字:")  
    findpdf = False  
  
    # 在缓存中搜索PDF文件  
    for pdf_path in pdf_cache[年份]:  
        if filename in os.path.basename(pdf_path):  
            os.startfile(pdf_path)  
            findpdf = True  
            break  
  
    if findpdf:  
        print("已为您打开质保书！")  
        for num in range(3, 0, -1):  
            print(f"{num}秒后继续打开....")  
            time.sleep(1)  
        print("==============")  
    else:  
        print(f"无法找到名为 {filename} 的质保书，请检查输入是否正确。")  
        for num in range(3, 0, -1):  
            print(f"{num}秒后继续打开....")  
            time.sleep(1)  
        print("==============")
